package com.fjnldx.mes.service.scheduling.alarm.rule.inspector;

import com.alibaba.fastjson.JSONObject;
import com.fjnldx.mes.domain.pojo.alarm.AlarmRules;
import com.fjnldx.mes.domain.pojo.alarm.enums.MonitoringTypeEnum;
import com.fjnldx.mes.service.scheduling.alarm.mapper.AlarmSchedulingMapper;
import com.fjnldx.mes.service.scheduling.alarm.model.MonitorModel;
import com.fjnldx.mes.service.scheduling.alarm.rule.inspector.trigger.AlarmTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据点检查
 */
@Service
public class DataPointsCheck implements AlarmRuleCheck {

    @Resource
    private AlarmSchedulingMapper alarmSchedulingMapper;

    private final List<AlarmTrigger> alarmTriggerList;

    DataPointsCheck(List<AlarmTrigger> alarmTriggers) {
        alarmTriggerList = alarmTriggers;
    }

    @Override
    public MonitoringTypeEnum monitoringType() {
        return MonitoringTypeEnum.DATA_POINTS;
    }

    @Override
    public MonitorModel Check(AlarmRules rule) {
        JSONObject monitor = JSONObject.parseObject(rule.getMonitorValue());
        //工序
        String dicBh = monitor.getString("dicBh");

        //设备编号
        String devSn = monitor.getString("devSn");

        //通过工序键查找实时表表名
        String tableName = alarmSchedulingMapper.mappingRelationTable(dicBh, devSn);

        //监控属性
        String cs = monitor.getString("cs");

        AlarmTrigger alarmTrigger = alarmTriggerList.stream().filter(trigger -> trigger.TriggerType() == rule.getTriggerType()).collect(Collectors.toList()).get(0);
        MonitorModel result = alarmTrigger.isTriggered(cs, tableName, devSn, rule.getTriggerValue(), null);
        if (result != null) {
            result.setDicBh(dicBh);
            result.setDevSn(devSn);
            result.setCs(cs);
            result.setCsName(monitor.getString("csName"));
        }
        return result;
    }
}
